package com.blink.curator.recipe.listener;

import com.blink.base.BaseTestSample;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.junit.jupiter.api.Test;

/**
 * <Description> 节点监听</Description>
 * <ClassName> NodeCacheSample</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月13日 16:14
 */
public class NodeCacheSample extends BaseTestSample {
    @Test
    public void testNodeCache() throws Exception {
        CuratorFramework client = getZkCurator();
        client.start();
        String path = "/zk-book/testNodeCache";
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(path, "init".getBytes());
        final NodeCache cache = new NodeCache(client, path, false);
        cache.start(true);
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                logger.info("Node data update, new data: " +
                        new String(cache.getCurrentData().getData()));
            }
        });
        client.setData().forPath(path, "u".getBytes());
        sleep(1);
        client.delete().deletingChildrenIfNeeded().forPath(path);
        sleep();
    }

    @Test
    public void testNodeCacheWithoutNode() throws Exception {
        CuratorFramework client = getZkCurator();
        client.start();
        String path = "/zk-book/curator_nodecache_sample";
        final NodeCache cache = new NodeCache(client, path, false);
        cache.start(true);
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                logger.info("Node data update, new data: " +
                        new String(cache.getCurrentData().getData()));
            }
        });
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(path, "init".getBytes());
        sleep();
    }

}
